package com.luci.security.support;

import com.luci.config.AuthProperties;
import com.luci.security.result.AuthResultAdapter;
import com.luci.security.result.JwtUser;
import com.luci.security.result.LoginException;
import com.luci.util.HttpServletResponseUtils;
import com.luci.util.JwtUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

/**
 * 登录处理默认实现
 *
 * @author yuyanan
 * @version 1.0
 * @date 18-11-14
 */
@Slf4j
public abstract class AbstractLoginAdapter<T extends ILoginBo> implements ILogin<T> {

    private static final String TOKEN_NAME = "token";
    private static final String USER_NAME = "user";

    /**
     * 配置属性
     */
    @Autowired
    protected AuthProperties authProperties;

    /**
     * 返回值
     */
    @Autowired
    private AuthResultAdapter authResult;

    @Override
    public void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {
        JwtUser jwtUser = (JwtUser) authentication.getDetails();
        String jwt = JwtUtils.buildJWT(jwtUser, authProperties.getSecret(), authProperties.getExpireDays());
        Map<String, Object> map = new HashMap<>(4);
        map.put(TOKEN_NAME, jwt);
        map.put(USER_NAME, jwtUser);
        AuthResultAdapter<Map> adapter = authResult.loginSuccess();
        adapter.setData(map);
        HttpServletResponseUtils.responseWrite(response, adapter);
    }


    @Override
    public void loginFail(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
            throws IOException {

        //处理登录异常
        if (exception instanceof LoginException) {
            log.warn("登录失败:{}", exception);
            LoginException le = (LoginException) exception;
            HttpServletResponseUtils.responseWrite(response, le.getError());
            return;
        }

        log.error("登录失败:{}", exception);
        HttpServletResponseUtils.responseWrite(response, authResult.loginFail());
    }


}
